package com.erp.service.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import android.os.Environment;

public class PropertyUtil
{
    private String dirname;
    private String filename;
    private String filepath;
    private String SDCardRoot;

    // 构造函数
    public PropertyUtil(String dirname, String filename)
    {
        super();
        this.dirname = dirname;
        this.filename = filename;
        SDCardRoot = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + File.separator;
        filepath = SDCardRoot + dirname + File.separator + filename;
        if (!isFileExist())
        {
            try
            {
                createFileInSDCard();
            }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }


    // 在SD卡中创建文件及其所在目录
    public File createFileInSDCard(String fileName, String dir)
            throws IOException
    {
        File dirFile = new File(SDCardRoot + dir);
        dirFile.mkdir();
        File file = new File(SDCardRoot + dir + File.separator + fileName);
        file.createNewFile();
        return file;
    }

    // 在SD卡中创建构造函数中文件及其所在目录
    public File createFileInSDCard() throws IOException
    {
        File dirFile = new File(SDCardRoot + dirname);
        dirFile.mkdir();
        File file = new File(filepath);
        file.createNewFile();
        return file;
    }
    // 从SD卡中删除指定的文件
    public void deleteFileInSDCard() throws IOException
    {
        File dirFile = new File(SDCardRoot + dirname);
        dirFile.mkdir();
        File file = new File(filepath);
        file.delete();
        return;
    }

    // 检查文件是否存在
    public boolean isFileExist(String fileName, String dirName)
    {
        File file = new File(SDCardRoot + dirName + File.separator + fileName);
        return file.exists();
    }

    // 检查构造传入的文件是否存在
    public boolean isFileExist()
    {
        File file = new File(filepath);
        return file.exists();
    }
    //检查配置文件中是否已经有key对应的记录，适用于properties类型的文件
		public boolean isRoomconfiged(String key){
			Properties prop = new Properties();
			try {
				BufferedReader br = new BufferedReader(new FileReader(filepath));
				prop.load(br);
				br.close();
				System.out.println(prop.getProperty(key));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}catch (NullPointerException e) {
				// TODO: handle exception
				return false;
			}
			return true;
		}

    // 根据键值返回对应的value值，适合properties类型的文件,效率比较高，不稳定
	public String readFromSDPropertiesFile(String key)
	{
		if(!isRoomconfiged(key)) {
			return null;
		}
		String ip = "";
		Properties prop = new Properties();
		try
		{
			BufferedReader br = new BufferedReader(new FileReader(filepath));
			prop.load(br);
			ip = prop.getProperty(key);
			br.close();
		}
		catch (IOException e)
		{ // TODO Auto-generated catch block e.printStackTrace();
		}
		return ip;
	}

    // 检查配置文件中是否已经有key对应的记录，如果有返回true,否则返回false（适用于properties类型的文件）
    public String readContentFromSDFile(String key)
    {
        String tmpStr = "";
        String[] s = null;
        FileReader fr;
        try
        {
            fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            while ((tmpStr = br.readLine()) != null)
            {
                s = tmpStr.split("\\=");
                if(s[0].equals("已配置列表")) {
                    continue;
                }else if (s[0].equals(key))
                {
                    if(s.length==2){
                        br.close();
                        fr.close();
                        return s[1];
                    }else{
                        br.close();
                        fr.close();
                        return "";
                    }
                }

            }
            br.close();
            fr.close();
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }

    // 根据键值修改配置文件中已经存在的一行内容，适用于properties类型的文件, 向文件中跟新数据(尾部添加)
    public void writeToSDFile(String key, String value)
    {
        String tmpStr = null;
        String[] s = null;
        int count = 0;
        FileReader fr;
        try
        {
            fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            StringBuilder sb = new StringBuilder();
            while ((tmpStr = br.readLine()) != null)
            {
                s = tmpStr.split("\\=");
                if (!s[0].equals(key)&&!s[0].equals("count"))
                {
                    sb.append(tmpStr);
                    sb.append("\r\n");
                    if(!s[0].equals("已配置列表")) {
                        count++;
                    }
                }
            }
            sb.append(key).append("=").append(value).append("\r\n");
            if(!key.equals("已配置列表")) {
                count++;
            }
            sb.append("count=").append(count);
            br.close();
            fr.close();
            FileOutputStream fos = new FileOutputStream(filepath);
            fos.write(sb.toString().getBytes());
            fos.flush();
            fos.close();
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public ArrayList<String> readKeysfromSDFile(){
        String tmpStr = null;
        String[] s;
        ArrayList<String> list = new ArrayList<String>();
        FileReader fr;
        try
        {
            fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            while ((tmpStr = br.readLine()) != null)
            {
                s = tmpStr.split("\\=");
                if(!s[0].equals("count")) {
                    list.add(s[0]);
                }
            }
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
    public void writeToUpdateKeyname(String oldkey,String newkey ,String value )
    {
        String tmpStr = null;
        String[] s = null;
        int count = 0;
        FileReader fr;
        try
        {
            fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            StringBuilder sb = new StringBuilder();
            while ((tmpStr = br.readLine()) != null)
            {
                s = tmpStr.split("\\=");
                if (s[0].equals(oldkey)&&!s[0].equals("count"))
                {
                    sb.append(newkey).append("=").append(value).append("\r\n");
                    count++;
                }else if(!s[0].equals("count")) {
                    sb.append(tmpStr);
                    sb.append("\r\n");
                    if(!s[0].equals("已配置列表")) {
                        count++;
                    }
                }

            }
            sb.append("count=").append(count);
            br.close();
            fr.close();
            FileOutputStream fos = new FileOutputStream(filepath);
            fos.write(sb.toString().getBytes());
            fos.flush();
            fos.close();
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public void deleteContent(String key) {
        String tmpStr = null;
        String[] s = null;
        int count = 0;
        FileReader fr;
        try
        {
            fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            StringBuilder sb = new StringBuilder();
            while ((tmpStr = br.readLine()) != null)
            {
                s = tmpStr.split("\\=");
                if (s[0].equals(key))
                {
                    continue;
                }else if(!s[0].equals("count")) {
                    sb.append(tmpStr);
                    sb.append("\r\n");
                    if(!s[0].equals("已配置列表")) {
                        count++;
                    }
                }

            }
            sb.append("count=").append(count);
            br.close();
            fr.close();
            FileOutputStream fos = new FileOutputStream(filepath);
            fos.write(sb.toString().getBytes());
            fos.flush();
            fos.close();
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public String getFilePath() {
        return filepath;
    }
    public String readLine(){
        FileReader fr;
        String str = null;
        try {
            fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            str= br.readLine();
            br.close();
            fr.close();
            if(str!=null){
                return str;
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
    //只改文件记录中第一个包含旧key的记录,针对大金空调软件设计的
    public void writeToUpdateKeynameFirst(String oldkey,String newkey ,String value )
    {
        String tmpStr = null;
        boolean firstdealed = false;;
        FileReader fr;
        try
        {
            fr = new FileReader(filepath);
            BufferedReader br = new BufferedReader(fr);
            StringBuilder sb = new StringBuilder();
            while ((tmpStr = br.readLine()) != null)
            {
                if (tmpStr.equals(oldkey)&&firstdealed == false)
                {
                    sb.append(newkey).append("\r\n").append(value).append("\r\n");
                    firstdealed = true;
                }else {
                    sb.append(tmpStr);
                    sb.append("\r\n");
                }

            }
            br.close();
            fr.close();
			/*File tmpFile = null;
			tmpFile = new File(SDCardRoot+dirname+File.separator+"tmp.txt");*/
            FileOutputStream fos = new FileOutputStream(filepath);
            fos.write(sb.toString().getBytes());
            fos.flush();
            fos.close();
		/*	tmpFile.renameTo(SDCardRoot+dirname)*/
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    public void writeGeneralFile(String str){
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(filepath);
            fos.write(str.getBytes("gb2312"));
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public byte[] readGeneralFile(){
        FileInputStream fis;
        int len = 0;
        byte[] buf = null;
        try {
            fis = new FileInputStream(filepath);
            len = fis.available();
            buf = new byte[len];
            fis.read(buf, 0, len);
            fis.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return buf;
    }
    public void copy(String dirName,String fileName){
        FileReader fr =null;
        BufferedReader br = null;
        File dirFile = null;
        StringBuilder sb = new StringBuilder();
        String str;
        try {
            createFileInSDCard(fileName, dirName);
            dirFile = new File(SDCardRoot+dirname+File.separator+"tmp.txt");
            fr = new FileReader(filepath);
            br = new BufferedReader(br);
            FileOutputStream fos = new FileOutputStream(dirFile);
            while ((str = br.readLine())!=null) {
                sb.append(str).append("\r\n");
            }
            fos.write(sb.toString().getBytes());
            fos.flush();
            fos.close();
            fr.close();
            br.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
